package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private CacheManager cacheManager;
    /**
     * 菜品信息分页
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        log.info("page={},pagesize={},name={}",page,pageSize,name);

        Page<Dish> dishPage = new Page(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> dqw = new LambdaQueryWrapper<>();

        dqw.like(StringUtils.isNotBlank(name),Dish::getName,name);
        dqw.eq(Dish::getIsDeleted,0);

        dqw.orderByDesc(Dish::getUpdateTime);

        dishService.page(dishPage,dqw);
        //对象拷贝
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //拿到dishPage中的records集合
        List<Dish> records = dishPage.getRecords();

//        遍历出每个菜品对象
        List<DishDto> list = new ArrayList<>();
        for (Dish record : records) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(record,dishDto);
            Long categoryId = record.getCategoryId();//菜品分类ID
            //拿到菜品分类对象，根据ID查询分类对象
            Category byId = categoryService.getById(categoryId);
            //拿到分类名称
            String name1 = byId.getName();
            //重新设置分类名称
            dishDto.setCategoryName(name1);
            list.add(dishDto);
        }
//        List<DishDto> list=records.stream().map((item)->{
//            DishDto dishDto = new DishDto();
//            BeanUtils.copyProperties(item,dishDto);
//            Long categoryId = item.getCategoryId();//菜品分类ID
//            //拿到菜品分类对象，根据ID查询分类对象
//            Category byId = categoryService.getById(categoryId);
//            if (byId!=null){
//                String name1 = byId.getName();
//                dishDto.setCategoryName(name1);
//            }
//            return dishDto;
//        }).collect(Collectors.toList());

       dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     * @CacheEvict只要出现dishController直接删除改缓存
     */
//    @CacheEvict(value = "dishController",allEntries = true)
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveFlavor(dishDto);
        String key ="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("成功");
    }
    /**
     * 回显修改菜品信息
     */
    @GetMapping("/{id}")
    public R<DishDto> getID(@PathVariable Long id){
        log.info("id={}",id);
        DishDto dishDto = dishService.get(id);
        return R.success(dishDto);
    }
    /**
     * 修改菜品信息
     * @CacheEvict只要出现dishController直接删除改缓存
     */
//    @CacheEvict(value = "dishController",allEntries = true)
    @PutMapping
    public R<String>update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());

        dishService.update(dishDto);
        String key ="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("ccc");
    }

    /**
     * 根据ID停售或起售
     */
    @PostMapping("/status/{status}")
    public R<String> setstatus(@PathVariable("status")int status, Long ids){
        Dish dish = new Dish();
        dish.setId(ids);
        dish.setStatus(status);
        dishService.updateById(dish);
        return R.success("成功");
    }

    /**
     * 根据ID删除
     * @param ids
     * @return
     * @CacheEvict只要出现dishController直接删除改缓存
     */
//    @CacheEvict(value = "dishController",allEntries = true)
    @DeleteMapping
    public R<String>delete(String ids){
        log.info(ids);
        String[] split = ids.split(",");
        for (String s : split) {
            Dish byId = dishService.getById(Long.parseLong(s));
        if (byId.getIsDeleted()!=1){
            byId.setIsDeleted(1);
        }
            dishService.updateById(byId);
        }
//        Dish byId = dishService.getById(ids);
//        if (byId.getIsDeleted()!=1){
//            byId.setIsDeleted(1);
//        }
        Dish byId2 = dishService.getById(ids);
        String key ="dish_"+byId2.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return  R.success("删除成功");
    }


//    @Cacheable(value = "dishController",key = "#dish.categoryId+'_'+#dish.status")
    @GetMapping("/list")
    public R<List<DishDto>>listR(Dish dish){
        ArrayList<DishDto> dishDtos =null;
        //动态构造key
        String key ="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        //先从redis中获取缓存数据
        dishDtos = (ArrayList<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos!=null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtos);
        }

        log.info(dish.toString());
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);
        queryWrapper.eq(Dish::getIsDeleted,0);
        queryWrapper.orderByDesc(Dish::getUpdateTime).orderByDesc(Dish::getSort);

        List<Dish> list = dishService.list(queryWrapper);
        ArrayList<DishDto> dishDtos1 = new ArrayList<>();
        for (Dish Dishlist : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(Dishlist,dishDto);
            Long categoryId = Dishlist.getCategoryId();
            Category byId = categoryService.getById(categoryId);
            if (byId!=null){
                String name = byId.getName();
                dishDto.setCategoryName(name);
            }
            Long id = Dishlist.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId,id);
            List<DishFlavor> dishFlavorlist = dishFlavorService.list(queryWrapper1);
            dishDto.setFlavors(dishFlavorlist);
            dishDtos1.add(dishDto);
        }
//        如果不存在，需要查询数据库，将查询到的菜品数据缓存到Reids
        redisTemplate.opsForValue().set(key,dishDtos1,60,TimeUnit.MINUTES);
        return R.success(dishDtos1);
    }
}
